import random

from django import forms
from django.conf import settings
from django.http import HttpResponse
from django.shortcuts import render

from app01 import models
from utils.tencent.sms import send_sms_single


def send_sms(request):
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    print(template_id)
    if not template_id:
        return HttpResponse('模板不存在')
    code = random.randrange(1000, 10000)
    print(code)
    res = send_sms_single('15071378813', template_id, [code, ])
    print(res)
    if res['result'] == 0:
        return HttpResponse('成功')
    else:
        return HttpResponse(res['errmsg'])


class RegisterModelForm(forms.ModelForm):
    password = forms.CharField(label='密码', widget=forms.PasswordInput())
    confirm_password = forms.CharField(label='重复密码', widget=forms.PasswordInput(
        attrs={'placeholder': '请重复密码'}))  # 可以使用这种attrs的方式，也可以用下面init的方式
    code = forms.IntegerField(label='验证码', max_value=9999, min_value=1000)

    class Meta:
        model = models.UserInfo

        # fields写成‘__all__’会默认顺序展示，如果想更换顺序，需要自己写
        # fields = '__all__'
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            if name == 'confirm_password':
                field.widget.attrs['placeholder'] = '请重复密码'
            else:
                field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)


def register(request):
    form = RegisterModelForm()
    return render(request, 'app01/register.html', {'form': form})
